<template>
  <view class="inspector-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="巡检人员信息" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 查询方式选择 -->
          <up-tabs :list="queryTypeList" :scrollable="false" @change="handleQueryTypeChange"></up-tabs>
          
          <!-- 搜索条件 -->
          <view class="search-section">
            <!-- 全部巡检员查询 -->
            <view v-if="currentQueryType === 0" class="search-item">
              <up-search v-model="searchForm.keyword" :clearabled="true" :showAction="true" 
                placeholder="请输入姓名或工号" @search="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                </template>
              </up-search>
            </view>
            
            <!-- 在岗巡检员查询 -->
            <view v-if="currentQueryType === 1" class="search-item">
              <up-search v-model="searchForm.keyword" :clearabled="true" :showAction="true" 
                placeholder="请输入姓名或工号" @search="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                </template>
              </up-search>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 汇总数据 -->
      <view v-if="summaryData" class="summary-section">
        <view class="summary-item">
          <text class="summary-label">在岗人数</text>
          <text class="summary-value count">{{ summaryData.onDutyCount }}人</text>
        </view>
        <view class="summary-item">
          <text class="summary-label">未签到人数</text>
          <text class="summary-value warning">{{ summaryData.notSignedCount }}人</text>
        </view>
        <view class="summary-item">
          <text class="summary-label">总人数</text>
          <text class="summary-value total">{{ summaryData.totalCount }}人</text>
        </view>
      </view>

      <!-- 列表内容 -->
      <view class="inspector-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              <text class="name">{{ item.name }}</text>
              <view class="status-badge" :class="{ 'signed': item.isSign === '1', 'not-signed': item.isSign === '0' }">
                {{ item.isSign === '1' ? '已签到' : '未签到' }}
              </view>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">账号：</text>
                <text class="value">{{ item.account }}</text>
              </view>
              <view class="item">
                <text class="label">手机号：</text>
                <text class="value">{{ item.phone }}</text>
              </view>
              <view class="item">
                <text class="label">管理场地：</text>
                <text class="value">{{ item.veNames }}</text>
              </view>
              <view class="item">
                <text class="label">账号类型：</text>
                <text class="value">{{ item.type === '4' ? '运维人员' : item.type === '6' ? '运维组长' : '其他' }}</text>
              </view>
              <view class="item">
                <text class="label">账号状态：</text>
                <text class="value">{{ item.status === '0' ? '正常' : '禁用' }}</text>
              </view>
              <view class="item">
                <text class="label">排班状态：</text>
                <text class="value">{{ item.isBan === '0' ? '未排班' : '已排班' }}</text>
              </view>
              <view class="item">
                <text class="label">离职状态：</text>
                <text class="value">{{ item.isResignation === '0' ? '未离职' : '已离职' }}</text>
              </view>
              <view class="item" v-if="item.remark">
                <text class="label">备注：</text>
                <text class="value">{{ item.remark }}</text>
              </view>
            </view>
            <view class="card-footer">
              <view class="operate">
                <up-button type="primary" text="地图位置" class="custom-style" 
                  @click="handleViewLocation(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 地图位置弹出层 -->
    <LocationModal v-model:show="showLocationModal" :inspector-info="selectedInspector" />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import LocationModal from './components/LocationModal.vue'
import { getInspectorList } from '@/api';

const { bool: showLocationModal, setTrue: openLocationModal, setFalse: closeLocationModal } = useBoolean();

// 查询方式选项卡数据
const queryTypeList = [
  { name: '全部巡检员' },
  { name: '在岗巡检员' },
];
const currentQueryType = ref(0);

// 搜索表单数据
const searchForm = reactive({
  keyword: '',
});

// 汇总数据
const summaryData = ref(null);

// 选中的巡检员信息
const selectedInspector = ref(null);

// z-paging 组件引用
const paging = ref(null)

// 当前显示的列表数据
const currentList = ref([])

// 查询方式切换事件
const handleQueryTypeChange = (e) => {
  const newIndex = e.index;
  if (currentQueryType.value === newIndex) {
    return;
  }

  currentQueryType.value = newIndex;
  
  // 清空搜索表单
  searchForm.keyword = '';
  
  // 清空列表和汇总数据
  currentList.value = [];
  summaryData.value = null;
  
  // 重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 搜索按钮点击事件
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 清空搜索
const handleClear = () => {
  searchForm.keyword = '';
  
  if (paging.value) {
    paging.value.reload();
  }
};

// 查看地图位置
const handleViewLocation = (item) => {
  selectedInspector.value = item;
  openLocationModal();
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}

// 获取巡检员列表数据
const queryList = async (pageNo, pageSize) => {
  console.log(pageNo, pageSize, currentQueryType.value)

  const params = {
    pageNum: pageNo,
    pageSize
  }

  await fetchList(params)
};

const fetchList = async (params) => {
  try {
    // 调用真实API获取数据
    const result = await getInspectorList(params);
    
    if (result && result.success) {
      const data = result.data;
      paging.value.complete(data.records || []);
      
      // 计算并设置汇总数据
      calculateSummary(data.records || [], data.total || 0);
    } else {
      uni.showToast({
        title: result.msg || '获取数据失败',
        icon: 'none'
      });
      paging.value.complete(false);
    }
  } catch (error) {
    console.error('获取巡检人员列表失败:', error);
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    });
    paging.value.complete(false);
  }
}

// 计算汇总数据
const calculateSummary = (records, total) => {
  if (!records || records.length === 0) {
    summaryData.value = {
      onDutyCount: 0,
      notSignedCount: 0,
      totalCount: 0
    };
    return;
  }
  
  // 计算在岗人数（已签到）
  const onDutyCount = records.filter(item => item.isSign === '1').length;
  
  // 计算未签到人数
  const notSignedCount = records.filter(item => item.isSign === '0').length;
  
  // 总人数
  const totalCount = total || records.length;
  
  summaryData.value = {
    onDutyCount,
    notSignedCount,
    totalCount
  };
};

// 页面挂载时获取数据
onMounted(() => {
  fetchList({
    pageNum: 1,
    pageSize: 10,
  })
});
</script>

<style scoped lang="scss">
.inspector-list {
  padding: 20px;
}

.search-section {
  margin-top: 20rpx;
  
  .search-item {
    margin-bottom: 20rpx;
  }
}

.summary-section {
  display: flex;
  justify-content: space-around;
  padding: 30rpx 40rpx;
  margin: 20rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16rpx;
  box-shadow: 0 8rpx 32rpx rgba(102, 126, 234, 0.3);
  
  .summary-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .summary-label {
      font-size: 24rpx;
      color: rgba(255, 255, 255, 0.8);
      margin-bottom: 8rpx;
    }
    
    .summary-value {
      font-size: 32rpx;
      font-weight: bold;
      color: #fff;
      
      &.count {
        color: #90ee90;
      }
      
      &.warning {
        color: #ffd700;
      }
      
      &.total {
        color: #87ceeb;
      }
    }
  }
}

// 列表卡片样式
.list-item-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;
  
  .card-header {
    padding: 24rpx 30rpx 16rpx;
    border-bottom: 1px solid #f5f5f5;
    
    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .name {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
      }
      
      .status-badge {
        padding: 4rpx 12rpx;
        border-radius: 12rpx;
        font-size: 22rpx;
        color: #fff;
        
        &.signed {
          background: #52c41a;
        }
        
        &.not-signed {
          background: #ff4d4f;
        }
      }
    }
  }
  
  .card-content-box {
    padding: 20rpx 30rpx;
    
    .content {
      .item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          font-size: 26rpx;
          color: #666;
          flex-shrink: 0;
        }
        
        .value {
          font-size: 26rpx;
          color: #333;
          text-align: right;
        }
      }
    }
    
    .card-footer {
      margin-top: 24rpx;
      padding-top: 20rpx;
      border-top: 1px solid #f5f5f5;
      
      .operate {
        display: flex;
        justify-content: flex-end;
        gap: 20rpx;
        
        .custom-style {
          border-radius: 8rpx;
          font-size: 24rpx;
        }
      }
    }
  }
}
</style>